#include "stdafx.h" 
#include <windows.h>
#include "serial.hpp"
#include <stdio.h>
#include <time.h>
#include <string>
#include <stdlib.h>

    Serial::Serial(){
    
    }
    
    int Serial::send(char *command, int bytes){
         int i=0;
         if (handle == INVALID_HANDLE_VALUE){
            return 0;
         }
         while(i<bytes){
            byte[i]=command[i];
            i++;
         }
         if(WriteFile(handle, byte, bytes, &nrBytes, NULL)!=0){
            return 1;      
         
         }
         else
            return 0;
    }    
    
    char *Serial::receive(int length){
        static char answer[MAX_NR_BYTES];
        int i=0;
        nrBytes=0;
        answer[0]='\0';
        if (ReadFile(handle, byte, length, &nrBytes, NULL) == 0){
            answer[0]='e';
            answer[1]='r';
            answer[2]='r';
            answer[3]='o';
            answer[4]='r';
            answer[5]='\0';
            return &answer[0];
        }
        //printf("Number of bytes %d\n",nrBytes);
        while(i<nrBytes){
            answer[i]=byte[i];            
            //printf("%d ",answer[i]);
            i++;
        }
        //printf("\n");
        answer[i]='\0';
        return &answer[0];
    }
    
    int Serial::flush(){
        int i=0;
//        clock_t endwait;
        //endwait = clock () + 1000 * CLK_TCK ;
        while(nrBytes > 0){
        
             if(ReadFile(handle, byte, 1, &nrBytes, NULL)==0){
                 return 0;
             }
             i++;
        }
        return i;
    }
    
    int Serial::connect(CString port){
        return connect(port, 200, 8, 19200, 0);    
    }

    int Serial::connect(CString port, int set_timeout, int bytesize, int baudrate, int parity){
        /***************************************************************************       
        *** See http://www.robbayer.com/files//serial-win.pdf for dokumentation  ****
        ***************************************************************************/    
        handle = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0,0,OPEN_EXISTING,0,0);
        if (handle == INVALID_HANDLE_VALUE){
            return 0;
        }
        dcb.ByteSize = bytesize;/*sets bit-size*/
        dcb.BaudRate = baudrate;/*sets baudrate*/
        /*Sets timeout for reading - 0 = deactivate*/
        timeout.ReadIntervalTimeout=set_timeout;
        timeout.ReadTotalTimeoutConstant=set_timeout;
        dcb.Parity=parity;
        timeout.ReadTotalTimeoutMultiplier=set_timeout;
        SetCommTimeouts(handle, &timeout);
        SetCommState(handle, &dcb);
        return 1;
    }
    
    int Serial::disconnect(){
          if (handle){
            CloseHandle(handle);
            return 1;
         }
         else{
            return 0;
        }
    }
